﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ODS.ViewModel;
using ODS.Model;
using ODS.WebService.DeviceFunctions;
using ODS.Utils;
using ODS.Config;
using System.Diagnostics;
using System.Windows.Media;

namespace ODS
{
    public partial class ActivatingDevice : PhoneApplicationPage
    {
        private DeviceModel currentDeviceModel;
        static bool isScanQRCodeSubscriptionCode = false;

        public ActivatingDevice()
        {
            InitializeComponent();

            //For scroll bottom menu
            MaxTranformY = (int)slidingMenu.Height - slidingMenu.GetHeightTopBar();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            currentDeviceModel = App.currentDeviceModel;
            tbl_deviceName.Text = currentDeviceModel.VehicleName.ToUpper();

            if (isScanQRCodeSubscriptionCode)
            {
                tb_subscritionCode.MyText = App.TextQRCode;
            }

            isScanQRCodeSubscriptionCode = false;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            scrollDownSlidingMenu();
            slidingMenu.HiddenImageSelected();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (!isMenuDowning)
            {
                scrollDownSlidingMenuWithAnimation();
                e.Cancel = true;
            }

            base.OnBackKeyPress(e);
        }

        #region events
        private void btn_scanSubscriptionCode_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            isScanQRCodeSubscriptionCode = true;
            this.NavigationService.Navigate(new Uri("/ScanQRCodePage.xaml", UriKind.Relative));
        }

        private void btn_setting_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/SettingPage.xaml", UriKind.Relative));
        }

        private void btn_back_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        private async void btn_active_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (tb_subscritionCode.MyText.Length > 0)
            {
                InfoResult result = await ActivateSubscriptionService.ActivateSubscription(currentDeviceModel, tb_subscritionCode.MyText);
                if (result.IsSuccess)
                {
                    if ((String)result.ReturnedObject == Constants.SUCCESS)
                    {
                        MessageBox.Show("Activate subscription successful.");
                    }
                    else
                    {
                        MessageBox.Show((String)result.ReturnedObject);
                    }
                }
                else
                {
                    MessageBox.Show(result.Error);
                }
            }
            else
            {
                MessageBox.Show("Empty SubscriptionCode field, please try again.");
            }
        }

        #endregion

        #region handle scroll bottom menu
        private void scrollDownSlidingMenu()
        {
            isMenuDowning = true;
            var transform = slidingMenu.RenderTransform as TranslateTransform;
            transform.Y = 0;
        }

        private void scrollDownSlidingMenuWithAnimation()
        {
            isMenuDowning = true;
            var transform = slidingMenu.RenderTransform as TranslateTransform;
            int Y = (int)transform.Y;
            AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);
        }



        private const int LIMIT_SCROLL = 100;
        bool isMenuDowning = true;
        int MaxTranformY = 0;
        private bool checkIsTapOnTopOfSlidingMenu(Point point)
        {
            GeneralTransform gt = ((UIElement)slidingMenu).TransformToVisual(this);
            Point pointOdSlidingMenu = gt.Transform(new Point(0, 0));

            if (point.Y >= pointOdSlidingMenu.Y && point.Y <= pointOdSlidingMenu.Y + slidingMenu.GetHeightTopBar())
                return true;
            return false;
        }

        Point Point_Start;
        Point point_Move;
        int offset = 0;

        bool IsMouseEnterOnTopBar = false;

        private void LayoutRoot_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Debug.WriteLine("LayoutRoot_MouseEnter");

            Point_Start = e.GetPosition((UIElement)sender);
            point_Move = Point_Start;

            if (checkIsTapOnTopOfSlidingMenu(Point_Start))
            {
                IsMouseEnterOnTopBar = true;

                if (!isMenuDowning)
                {
                    slidingMenu.UnRegisterEventMouseForGrids();
                }

            }
            else
                IsMouseEnterOnTopBar = false;
        }

        private void LayoutRoot_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (isTap)
            {
                isTap = false;
                return;
            }

            if (!IsMouseEnterOnTopBar)
                return;

            if (slidingMenu.IsUnRegisterEventMouseForGrids)
            {
                slidingMenu.RegisterEventMouseForGrids();
            }

            Debug.WriteLine("LayoutRoot_MouseLeave");
            var transform = slidingMenu.RenderTransform as TranslateTransform;
            int Y = (int)transform.Y;

            if (transform.Y < -(MaxTranformY - LIMIT_SCROLL))
            {
                //sb_scrollMenuUp.Begin();

                AnimationUtil.getInstance().startAnimation(slidingMenu, Y, -MaxTranformY);
                isMenuDowning = false;
            }
            else if (transform.Y > -LIMIT_SCROLL)
            {
                //sb_scrollMenuDown.Begin();

                AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);
                isMenuDowning = true;
            }
            else
            {
                if (offset > 0)
                {
                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);
                    isMenuDowning = true;
                }
                else
                {
                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, -MaxTranformY);
                    isMenuDowning = false;
                }
            }
        }

        private void LayoutRoot_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Debug.WriteLine("LayoutRoot_MouseMove");

            if (!IsMouseEnterOnTopBar)
                return;

            var transform = slidingMenu.RenderTransform as TranslateTransform;

            point_Move = e.GetPosition((UIElement)sender);

            offset = (int)(point_Move.Y - Point_Start.Y);

            Point_Start = point_Move;

            Debug.WriteLine("offset: " + offset);

            if ((transform.Y <= -MaxTranformY && offset < 0))
            {
                isMenuDowning = false;
                return;
            }

            if ((transform.Y >= 0 && offset > 0))
            {
                isMenuDowning = true;
                return;
            }

            transform.Y += offset;

            if (transform.Y < -MaxTranformY)
                transform.Y = -MaxTranformY;
            if (transform.Y > 0)
                transform.Y = 0;

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {

                slidingMenu.UpdateLayout();
            });


            Debug.WriteLine("MouseMove: " + point_Move);
        }

        bool isTap = false;

        private void LayoutRoot_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Debug.WriteLine("LayoutRoot_Tap");
            isTap = true;

            Point Point_click = e.GetPosition((UIElement)sender);

            if (checkIsTapOnTopOfSlidingMenu(Point_click))
            {
                var transform = slidingMenu.RenderTransform as TranslateTransform;
                int Y = (int)transform.Y;


                if (isMenuDowning)
                {
                    //sb_scrollMenuUp.Begin();

                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, -MaxTranformY);
                    isMenuDowning = false;
                }
                else
                {
                    //sb_scrollMenuDown.Begin();

                    AnimationUtil.getInstance().startAnimation(slidingMenu, Y, 0);
                    isMenuDowning = true;
                }
            }

            if (slidingMenu.IsUnRegisterEventMouseForGrids)
            {
                slidingMenu.RegisterEventMouseForGrids();
            }
        }

        #endregion
    }
}